package com.fjnu.controller;

import com.fjnu.domain.dto.ArticleConditionDto;
import com.fjnu.domain.dto.ArticleDto;
import com.fjnu.domain.dto.ArticleUpdateDto;
import com.fjnu.domain.entity.Article;
import com.fjnu.domain.vo.ResponseResult;
import com.fjnu.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/blog-api/v0.1/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping("/list")
    public ResponseResult<List<Article>> list(@RequestBody ArticleConditionDto articleCond) {
        // 参数验证
        if (articleCond == null) {
            throw new IllegalArgumentException("查询条件不能为空");
        }

        var pageResult = articleService.queryByArticleCondition(articleCond, 1, 10);

        if (pageResult == null) {
            throw new RuntimeException("查询服务返回空结果");
        }

        if (pageResult.getData() == null || pageResult.getData().isEmpty()) {
            return ResponseResult.success("查询成功，但未找到匹配的文章", Collections.emptyList());
        }

        return ResponseResult.success("查询成功", pageResult.getData());
    }

    @PostMapping("/add")
    public ResponseResult<String> add(@RequestBody ArticleDto articleDto) {
        Article article = new Article();
        article.setTitle(articleDto.getTitle());
        article.setContent(articleDto.getContent());
        article.setUserId(articleDto.getUserId());
        article.setCategoryId(articleDto.getCategoryId());
        article.setDescription(articleDto.getDescription());
        article.setCoverImg(articleDto.getCoverImg());

        Article result = articleService.insertArticle(article);
        if (result != null) {
            return ResponseResult.success("文章添加成功");
        }
        return ResponseResult.error("文章添加失败");
    }

    @PostMapping("/update")
    public ResponseResult<String> update(@RequestBody ArticleUpdateDto articleUpdateDto) {
        int result = articleService.updateArticle(articleUpdateDto);
        if (result > 0) {
            return ResponseResult.success("文章更新成功");
        }
        return ResponseResult.error("文章更新失败");
    }

    @GetMapping("/{id}/publish")
    public ResponseResult<String> publish(@PathVariable String id) {
        String userId = "1"; // 实际应从会话中获取，这里假设都是用户1
        int result = articleService.publishArticle(id, userId);
        if (result > 0) {
            return ResponseResult.success("文章发布成功");
        }
        return ResponseResult.error("文章发布失败");
    }
}